package com.java.array;


/**
 * @Author hyx
 * @Description TODO
 * @Date 2024/3/3 21:56
 * @Version 1.0
 */
public class ArrayTest {
    public static void main(String[] args) {
        int[] array = {4,1,5,12,15,18,11,9,21,23,6,9,12};
        ArrayDemo.printArray(array);
        int[] sortArray = ArrayDemo.selectSort(array);
        System.out.println("sortArray.length ="+sortArray.length);
        ArrayDemo.printArray(sortArray);
        int index = binarySearch(sortArray,9);
        System.out.println("key在数组中的角标为"+index);
    }

    /**
     * 二分查找原理，找出有序数组中key所在的角标，没有返回-1
     * @param sortArray 有序数组
     * @param key
     */
    private static int binarySearch(int[] sortArray, int key) {
        int min =0, max = sortArray.length-1, mid;
        while(min <= max){
            mid = (min +max) >>1;
            if(key >sortArray[mid] ){
                min = mid +1;
            }else if(key < sortArray[mid]){
                max = mid -1;
            }else{
                return mid;
            }
        }
        return -1;
    }
}
